﻿using System;
using System.Collections.Generic;
using ch11.interpreter;

namespace ch11.instance
{
    public struct NativeModule : IModule
    {
        private Dictionary<string, object> exported;

        public static NativeModule NewNativeInstance()
        {
            return new()
            {
                exported = new Dictionary<string, object>()
            };
        }

        public void RegisterFunc(string nameAndSig, SharpFunc f)
        {
            var (name, sig) = SigParser.ParseNameAndSig(nameAndSig);
            exported[name] = new NativeFunction {t = sig, f = f};
        }

        public object GetMember(string name)
        {
            return exported[name];
        }

        public (object[], Exception) InvokeFunc(string name, params object[] args)
        {
            try
            {
                var d = (IFunction) exported[name];
                return d.Call(args); // TODO
            }
            catch (Exception e)
            {
                return (null, e);
            }
        }

        public (object, Exception) GetGlobalVal(string name)
        {
            var g = (IGlobal) exported[name];
            return (g.Get(), null); // TODO
        }

        public Exception SetGlobalVal(string name, object val)
        {
            ((IGlobal) exported[name]).Set(val); // TODO
            return null;
        }
    }
}